<?php
namespace app\admin\controller\routes;
use service\JsonService;
use app\common\model as M;

/**
 * 线路管理
 */
class Routes extends \app\admin\controller\AuthController
{
	public $model = '\app\common\model\Routes';

    use \traits\ShotcutControllerTrait;

    protected function _save( array $data )
    {
        if ( isset($data['label']) && is_array($data['label']) ) {
            $data['label'] = json_encode($data['label']);
        }

        if ( isset($data['albums']) && is_array($data['albums']) ) {
            $data['albums'] = json_encode($data['albums']);
        }
        return $data;
    }

    public function preparePrimePriceOptions()
    {
        $options = M\UserLevel::query("
            SELECT 0 as level_id,0 as grade_type,0 as level_price

            UNION

            SELECT id as level_id,grade_type,0 as level_price FROM `eb_user_level` WHERE status = 1 ORDER BY grade_type ASC
        ");

        if ( !empty($options) ) {
            foreach ( $options as &$option ) {
                $option['grade_type_display'] = M\UserLevel::$grade_type[$option['grade_type']] ?? '普通用户';
            }
        }

        return JsonService::successful($options);
    }

    /**
     * 生成SKU配置
     * @Author   FW
     * @DateTime 2024-02-29
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function generateSkuConfig()
    {
        $post = $this->request->post();
        if ( empty($post['allowSoldMonthes']) ) return JsonService::fail('缺少allowSoldMonthes');
        if ( empty($post['big_room']) ) $post['big_room'] = 0; //return JsonService::fail('缺少big_room');
        if ( empty($post['double_room']) ) $post['double_room'] = 0;//return JsonService::fail('缺少double_room');
        if ( empty($post['holiday_plus']) ) $post['holiday_plus'] = 0;
        if ( empty($post['prices']) ) return JsonService::fail('缺少prices');
        if ( empty($post['store']) ) $post['store'] = 0;//return JsonService::fail('缺少store');
        if( !is_array($post['allowSoldMonthes']) ) return JsonService::fail('月份格式错误');

        $fixWeeks = $post['fix_weeks'] ?? [];

        $daysGroup = [];
        foreach ( $post['allowSoldMonthes'] as $month ) {
            $start = new \DateTime("first day of $month");
            $end   = new \DateTime("last day of $month");

            $month_days = [];
            for( $time = $start; $time <= $end; $time = $time->modify("+1 day") ) {
                $month_days[] = $time->format('Y-m-d');
            }
            $final_data = [];

            foreach ( $month_days as $month_day ) {
                $month_day_time = strtotime($month_day);
                $week = date('w' , $month_day_time);
                $date = date('Y-m-d' , $month_day_time);

                $isFixedWeek = 0;
                if ( !empty($fixWeeks) ) {
                    if ( in_array($week , $fixWeeks) ) $isFixedWeek = 1;
                }

                $prices = [];
                foreach ( $post['prices'] as $k => $price ) {
                    if ( $isFixedWeek==1 ) {
                        $price['level_price'] = ($week == 5 || $week == 6 || $week == 0) ? ($price['level_price']+$post['holiday_plus']) : $price['level_price'];
                    } else {
                        $price['level_price'] = 0;
                    }
                    $prices[] = $price;
                }

                $final_data[] = [
                    'day'         => (int)date('d' , $month_day_time),
                    'week'        => (int)$week,//$week == 0 ? 7 : $week,
                    'week_display'=> dateToWeek($date),
                    'date'        => $month_day,
                    'prices'      => $prices,
                    'store'       => $isFixedWeek==1?$post['store']:0,
                    'double_room' => $isFixedWeek==1?$post['double_room']:0,
                    'big_room'    => $isFixedWeek==1?$post['big_room']:0,
                ];
            }

            $daysGroup[] = [
                'month' => $month,
                'days'  => $final_data
            ];
        }
        return JsonService::successful($daysGroup);
    }

    /**
     * 获取SKU
     * @Author   FW
     * @DateTime 2024-03-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function getSkuList()
    {
        $route_id = (int)input('route_id');
        $skus = M\RoutesSku::where('route_id',$route_id)->select();
        return JsonService::successful($skus);
    }

    /**
     * 保存单个SKU
     * @Author   FW
     * @DateTime 2024-03-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveSku()
    {
        $post = $this->request->post();
        if ( empty($post['sku_name']) ) return JsonService::fail('名称不能为空');
        if ( empty($post['route_id']) ) return JsonService::fail('所属线路不能为空');

        $skuInfo = [];
        if ( !empty($post['id']) ) {
            $skuInfo['id'] = (int)$post['id'];
        }
        $skuInfo['route_id'] = $post['route_id'];
        $skuInfo['sku_name'] = $post['sku_name'];
        $res = M\RoutesSku::saveOne($skuInfo);
        return JsonService::successful('操作成功');
    }

    /**
     * 获取SKU价格
     * @Author   FW
     * @DateTime 2024-04-11
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function getSkuPrice()
    {
        $skuId   = (int)input('sku_id');
        $monthes = json_decode(M\RoutesSku::where('id',$skuId)->value('allow_sold_monthes'));
        if ( empty($monthes) ) return JsonService::fail('无数据');

        $list = [];
        foreach ( $monthes as $month ) {
            $days = M\RoutesSkuPrice::field('id,date,origin_store as store,double_room,big_room')->with('prices')->where('sku_id',$skuId)->where('date','LIKE', "$month%")->order('date ASC')->select();
            if ( !empty($days) ) {
                $days = $days->toArray();
                foreach ( $days as &$day ) {
                    $day['day']  = (int)date('d' , strtotime($day['date']));
                    $day['week'] = (int)date('w' , strtotime($day['date']));
                    $day['week_display'] = dateToWeek($day['date']);
                }
            }

            $list[] = [
                'month' => $month,
                'days'  => $days
            ];
        }
        return JsonService::successful($list);
    }

    /**
     * 保存库存价格设置
     * @Author   FW
     * @DateTime 2024-03-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveSkuPrice()
    {
        $skuId    = (int)input('sku_id');
        $route_id = (int)input('route_id');
        $post   = $this->request->post();
        $config = $post['config'];

        $monthes = [];
        $priceData = [];
        foreach ( $config as $cfg ) {
            if ( empty($cfg['month']) || empty($cfg['days']) ) continue;

            $monthes[] = $cfg['month'];

            foreach ( $cfg['days'] as $day ) {
                $priceData = [
                    'route_id'  => $route_id,
                    'sku_id'    => $skuId,
                    'date'      => $day['date'],
                    'origin_store' => $day['store'],
                    // 'double_room'  => $day['double_room'],
                    // 'big_room'     => $day['big_room'],
                    'left_store'   => $day['store'],
                ];
                $skpId = M\RoutesSkuPrice::saveOne($priceData);
                if ( !empty($day['prices']) ) {
                    foreach ( $day['prices'] as $price ) {
                        $primePrices = [
                            'route_id'           => $route_id,
                            'skp_id'             => $price['skp_id'] ?? $skpId,
                            'grade_type'         => $price['grade_type'],
                            'grade_type_display' => M\UserLevel::$grade_type[$price['grade_type']] ?? '普通用户',
                            'level_id'           => $price['level_id'],
                            'level_price'        => $price['level_price'],
                        ];
                        M\RoutesSkuPricePrime::saveOne($primePrices);
                    }
                }
            }
        }
        $skuInfo = [
            'id' => $skuId,
            'allow_sold_monthes' => json_encode($monthes)
        ];
        M\RoutesSku::saveOne($skuInfo);
		
		## 回写线路最小价格冗余
		$minPrice = M\RoutesSkuPricePrime::where('route_id',$route_id)->where('level_price>0')->where('level_id',0)->MIN('level_price');
        $minPrime = M\RoutesSkuPricePrime::where('route_id',$route_id)->where('level_price>0')->where('level_id','gt',0)->MIN('level_price');
		M\Routes::where('id',$route_id)->update(['price' => $minPrice,'prime_price' => $minPrime]);
		
        return JsonService::successful('操作成功');
    }

    /**
     * 保存详情模块
     * @Author   FW
     * @DateTime 2024-03-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveDetailsMod()
    {
        $route_id  = (int)input('route_id');
        $mod_title = input('mod_titlt');
        $sort      = (int)input('sort');
        if ( empty($mod_title) ) return JsonService::fail('模块名称必填');

        if ( $route_id > 0 ) {
            if ( M\RoutesDetails::where('route_id',$route_id)->where('mod_title',$mod_title)->count() > 0 ) return JsonService::fail('模块已存在');

            $details = new M\RoutesDetails;
            $details->route_id  = $route_id;
            $details->mod_title = $mod_title;
            $details->sort      = $sort;
            $res = $details->save();
            if ( $res === false ) return JsonService::fail('添加失败');

            return JsonService::successful($details);
        }
        return JsonService::fail('添加失败');
    }

    /**
     * 获取详情秀米平台编辑链接
     * @Author   FW
     * @DateTime 2024-03-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function getDetailsEditUrl($id)
    {
        // $cachedSyncArticle = \think\Cache::get(\service\XiumiEditorService::SYNC_ARTICL_KEY);
        // if ( !empty($cachedSyncArticle) ) return JsonService::fail('缓存中存在冲突图文，请等待结束后再操作');

        $details = M\RoutesDetails::where('id',$id)->find();
        if ( empty($details) ) return JsonService::fail('详情不存在');

        \think\Cache::set(\service\XiumiEditorService::SYNC_ARTICL_KEY , $details , 1800);
        $url = (new \service\XiumiEditorService)->generateEditUrl($details->article_id);
        return JsonService::successful(['url' => $url]);
    }

    /**
     * 删除线路模块详情
     * @Author   FW
     * @DateTime 2024-03-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function deleteDetails($id)
    {
        $res = M\RoutesDetails::where('id',$id)->delete();
        if ( $res === false ) return JsonService::fail('删除失败');

        return JsonService::successful();
    }

    
}//Class End